package top.haijunit.work.utils;

import cn.hutool.json.JSONUtil;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import top.haijunit.work.core.doamin.ExceptionServer;
import top.haijunit.work.core.doamin.Result;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * web工具类
 *
 * @author zhanghaijun
 * @since 2024-09-10
 */
@Slf4j
@UtilityClass
public class SpringWebUtils extends org.springframework.web.util.WebUtils {

    /**
     * 获取response对象
     */
    public static HttpServletResponse getResponse() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        Assert.notNull(requestAttributes, "response from RequestContextHolder is null");
        return requestAttributes.getResponse();
    }

    /**
     * 获取request对象
     */
    public static HttpServletRequest getRequest() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        Assert.notNull(requestAttributes, "request from RequestContextHolder is null");
        return requestAttributes.getRequest();
    }

    /**
     * 获取请求路径
     */
    public static String getRequestURI() {
        return getRequest().getRequestURI();
    }

    /**
     * 请求转发
     */
    public void forward(String url) {
        HttpServletRequest request = getRequest();
        HttpServletResponse response = getResponse();
        try {
            request.getRequestDispatcher(url).forward(request, response);
        } catch (Exception e) {
            log.error("转发失败：{}", url, e);
            throw new ExceptionServer("路径转发失败，{}", url, e);
        }
    }

    public static void writeJson(HttpServletResponse response, Result<String> result) throws IOException {
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(JSONUtil.toJsonStr(result).getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}
